package com.knight.admin.service;

import java.util.Date;

import org.apache.log4j.Logger;

import com.jfinal.plugin.activerecord.Page;
import com.knight.admin.common.constant.Constant;
import com.knight.admin.model.Project;
import com.knight.admin.utils.FileUtils;

public class ProjectService {

	private static final Logger logger = Logger.getLogger(ProjectService.class);

	private static ProjectService instance = new ProjectService();

	private ProjectService() {
	}

	public static ProjectService getInstance() {
		return instance;
	}

	private final static Project dao = new Project().dao();

	/**
	 * 通过菜单Id查询项目
	 * 
	 * @param type
	 * @return
	 */
	public Page<Project> findProjectByMenuId(int pageNum, int pageSize, String menuId) {
		return dao.paginate(pageNum, pageSize, "SELECT *",
				"FROM project WHERE menuId=" + menuId + " ORDER BY createDate DESC");
	}

	public void saveProject(String showUrl, String urls, Project project) {
		project.setUrls(urls);
		project.setShowUrl(showUrl);
		project.setcreateDate(new Date());
		project.save();
	}

	public Project findById(Integer id) {
		return dao.findById(id);
	}

	public boolean deleteById(Integer id) {

		Project p = findById(id);
		if (p == null) {
			logger.error("通过id为" + id + "删除project失败");
			return false;
		}
		String urls = p.getUrls();
		logger.debug("-------start delete image-------");
		if (urls.contains(Constant.Symbo.COMMA)) {
			// 包含逗号
			for (String url : urls.split(Constant.Symbo.COMMA)) {
				FileUtils.deleteFile(url);
			}
		} else {
			FileUtils.deleteFile(urls);
		}
		logger.debug("-------end delete image-------");
		return dao.deleteById(id);
	}
}
